package RadianceM.DistributionSystem.controller;

import RadianceM.DistributionSystem.dto.Authority;
import RadianceM.DistributionSystem.dto.LoginInfo;
import RadianceM.DistributionSystem.entity.User;
import RadianceM.DistributionSystem.service.UserService;
import RadianceM.DistributionSystem.voto.result.DSResult;
import RadianceM.DistributionSystem.voto.result.ResultCode;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Length;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@Validated
@RestController
@Tag(name = "用户登录接口",description = "用户通过输入部分信息获取本系统的使用权限的API")
@ApiResponses(@ApiResponse(responseCode = "200", description = "接口请求成功"))
@RequestMapping("/users/login")
public class LoginController {
	@Resource
	protected UserService userService;

	@Operation(summary = "默认登录方式",description="通过账号密码进行登录")
	@Parameters({
			@Parameter(name = "username", description = "用户账号", required = true, example = "04211429"),
			@Parameter(name = "password", description = "密码", required = true, example = "123456789")
	})
	@RequestMapping(value = "/byPassword",method = RequestMethod.POST)
	public DSResult<LoginInfo> loginByPassword(
			@NotNull @Length(min = 6,max = 15)
			@RequestParam("username")
			String username,
			@NotNull @Length(min = 8,max = 15)
			@RequestParam("password")
			String password
	) {
		Map<String,Object> loginBoto = userService.loginByPassword(username, password);
		return switch (
				(Integer) loginBoto.get("status")) {
			case 200 -> DSResult.success(
					new LoginInfo(
							(Authority) loginBoto.get("authority"),
							(String)loginBoto.get("token")
					)
			);
			case 201 -> DSResult.fail(ResultCode.USER_ACCOUNT_NOT_EXIST);
			case 202 -> DSResult.fail(ResultCode.USER_CREDENTIALS_ERROR);
			default -> DSResult.fail(ResultCode.SYSTEM_ERROR);
		};
	}
	
}
